/*
Firefox Midas Handling code (Rich text editing)
-----------------------------------------------------

A portion of this code is derived from GPL 2.0 code originally by David Murray, author of the outstanding DeepestSender extension (http://deepestsender.mozdev.org)
Original note by David Murray:
This lot of code is half made up from Mozilla.org's Midas demo (http://www.mozilla.org/editor/midasdemo/)
and Netscape DevEdge's demo of the control also (http://devedge.netscape.com/viewsource/2003/midas/01/).
*/

var gPerFormancingColorPick = false; //Keep color picker from triggering twice (bad hack)
var performancingMidas = new Object();
var performancingTextEdit = new Object();

performancingMidas.prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService)
	.getBranch("performancing.");
performancingMidas.selectedTab = 0;

performancingMidas.setUpMidas = function() {
	// Set colorpicker to black.
	document.getElementById("performance-color-picker").color = "#000000";
    
    var editor = document.getElementById("performancing-message");
    getContentWindow(editor).document.designMode = 'on';

    var source = document.getElementById("performancing-message-source");
	
	var useCSS = this.prefs.getBoolPref("settings.usecss");
	getContentWindow(editor).document.execCommand("styleWithCSS", false, useCSS);
}

performancingMidas.makeBlank = function() {
    // This is to blank out the iframe, for if a post has been sent succesfully or whatever.
    var midas = document.getElementById("performancing-message");
    var SourceTextBox = document.getElementById("performancing-message-source");
    var subjectTextBox = document.getElementById("performancing-editor-subject");
    var winPreview = document.getElementById("performancing-preview-display");

    try{
        getContentWindow(winPreview).contentDocument.documentElement.innerHTML = "";
    } catch(e){ }

    SourceTextBox.value = "";
    subjectTextBox.value = "";
    getContentWindow(midas).document.body.innerHTML = "<br/>";
    getContentWindow(midas).document.designMode = "on";
    
    var useCSS = this.prefs.getBoolPref("settings.usecss");
    getContentWindow(midas).document.execCommand("styleWithCSS", false, useCSS);
    getContentWindow(midas).document.body.innerHTML = "<br/>";
    getContentWindow(midas).focus()
}

performancingMidas.doSomeEditCommand = function(aName, aArg) {
    var bfEditorTabSelected = document.getElementById("performancing-editor-tabbox").selectedIndex;
    if(bfEditorTabSelected == 1){
        performancingTextEdit.insertCode(aName, null, null);
    }else{
        this.doRichEditCommand(aName, aArg);
    }
} 

performancingMidas.doRichEditCommand = function(aName, aArg) {
    var midas = document.getElementById("performancing-message");
	
    // substitute undefined command identifiers
    getContentWindow(midas).document.execCommand(aName, false, aArg);
    getContentWindow(midas).focus()
} 

performancingMidas.addLink = function(){
	var midas = document.getElementById("performancing-message");
	
	if (document.getElementById("performancing-editor-tabbox").selectedIndex == '1'){
		performancingTextEdit.insertCode('url', null, null);
	}
	else {
		var localeString = performancingUI.getLocaleString('midaseenterurl');
		var checkString = performancingUI.getLocaleString('openinnewwindow');
		var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
			.getService(Components.interfaces.nsIPromptService);
			
		try {
			var cbUrl = pff_getClipboardContents();

			if (cbUrl && cbUrl.match(/^http/i)) {
				var defaultValue = cbUrl;
			}
			else {
				try {
					var defaultValue = pffEditorUI.parentWindow.content.document.location.href;
				} catch (e) {
					var defaultValue = "http://";
				}
				
				if (defaultValue.match(/^chrome/)) defaultValue = "http://";
			}
			
			if (defaultValue.match(/^chrome/)) defaultValue = "http://";
		} catch (e) {
			var defaultValue = "http://";
		}
		
		var input = { value: defaultValue };
		var checked = performancingMidas.prefs.getBoolPref("editor.openInNewWindow");
		var check = { value: checked };
		
		var okorcancel = prompts.prompt(window, localeString, localeString, input, checkString, check);
		
		if (okorcancel) {
		    performancingMidas.prefs.setBoolPref("editor.openInNewWindow", check.value);
		    
			if (input.value == '') {
				var e = midas.getHTMLEditor(getContentWindow(midas)).getSelectedElement("A");
				
				if (e) {
					e.removeAttribute("href");
				}
			}
			else {
				var nonce = '';
				
				if (check.value) {
					nonce = Math.round(Math.random() * 1000);
				}
				
				if (getContentWindow(midas).document.execCommand("createLink", false, nonce + input.value)) {
					if (check.value) {
						var parent = midas.getHTMLEditor(getContentWindow(midas)).getSelectionContainer();
						var links = getContentWindow(midas).document.getElementsByTagName("a");
						
						for (var i = 0; i < links.length; i++) {
							if (links.item(i).getAttribute("href") == (nonce + input.value)) {
								links.item(i).setAttribute("target", "_blank");
								links.item(i).href = input.value;
							}
						}
					}
				}
			}
		}
	}
}

performancingMidas.blockquote = function(){
	var bfEditorTabSelected = document.getElementById("performancing-editor-tabbox").selectedIndex;
	
	if(bfEditorTabSelected == '1'){
		performancingTextEdit.insertCode('blockquote', null, null);
	}
	else{
		this.doRichEditCommand('formatblock', 'blockquote');
		
		// Leave some room to exit the blockquote.
    	var winNormal = document.getElementById("performancing-message");
		getContentWindow(winNormal).document.body.innerHTML += "<br /><br />";
	}
}

performancingMidas.strong = function(){
  performancingMidas.doApplyTag("strong");
}

performancingMidas.customtag = function() {
	var tag = null;
	tag = prompt(performancingUI.getLocaleString("customTag"));
	if (tag != null) {
		performancingMidas.doApplyTag(tag);
	}
}

performancingMidas.em = function(){
  performancingMidas.doApplyTag("em");
}

performancingMidas.doApplyTag = function(sTagName) {
	var editorTab = document.getElementById("performancing-editor-tabbox").selectedIndex;
	
	if (editorTab == '1') {
		// HTML Editor.
		performancingTextEdit.insertCode(sTagName, null, null);
	} else { 
		var midas = document.getElementById("performancing-message");
		var oRange = getContentWindow(midas).getSelection().getRangeAt(0);  // this will exist only in the rich text editor

		if(performancingMidas.isTagPresent(sTagName, oRange) && !oRange.collapsed) {
			// Selecting a range that includes the tag, in the WYSIWYG editor.
			performancingMidas.removeTag(oRange);
		} else {
			// Add the tag, in the WYSIWGY editor.
			var winNormal = document.getElementById("performancing-message");
			var html = getContentWindow(winNormal).document.body.innerHTML;

			this.doRichEditCommand('formatblock', sTagName);

			var newHtml = getContentWindow(winNormal).document.body.innerHTML;

			if (html == newHtml) {
				var oRange = getContentWindow(midas).getSelection().getRangeAt(0);
				var totalHTML = getContentWindow(midas).document.body.innerHTML;

				var contents = oRange.extractContents();

				var newTotalHTML = getContentWindow(midas).document.body.innerHTML;

				var start = 0;

				var firstPart = "";
				var lastPart = "";

				for (start = 0; start < totalHTML.length; start++) {
					if (totalHTML[start] != newTotalHTML[start]) {
						firstPart = newTotalHTML.substring(0, start);
						lastPart = newTotalHTML.substring(start);
						break;
					}
				}

				if (firstPart == "" && lastPart == "") {
					firstPart = newTotalHTML;
				}

				var diff = totalHTML.length - newTotalHTML.length;
				var selectedHTML = totalHTML.substring(start, start + diff);
				getContentWindow(midas).document.body.innerHTML = firstPart + "<"+sTagName+">" + selectedHTML + "</" + sTagName + ">" + lastPart;
			}
		}
	
		if (oRange) {
			oRange.detach();
		}
	}
}

performancingMidas.isTagPresent = function(sTagName, oRange) {
  sTagName = sTagName.toUpperCase();
  if(oRange.startContainer.parentNode.nodeName == sTagName || oRange.endContainer.parentNode.nodeName == sTagName)
    return true;
  else
    return false;
}

performancingMidas.removeTag = function(oRange) {
  var sRange = oRange.toString();
  var midas = document.getElementById("performancing-message");
  oRange.deleteContents();
  oRange.insertNode(getContentWindow(midas).document.createTextNode(sRange));
  sRange = null;
  return false;
}

//Not used blockquote
performancingMidas.bold = function(){
        var midas = document.getElementById("performancing-message");
        var bfEditorTabSelected = document.getElementById("performancing-editor-tabbox").selectedIndex;
        if(bfEditorTabSelected == '1'){
            performancingTextEdit.insertCode('url', null, null);
        }else{
            var strong = getContentWindow(midas).document.createElement("strong");
            var sel = getContentWindow(midas).getSelection();
            var range = sel.getRangeAt(0);
            var beforeNode = range.extractContents();
            //var beforeNode = document.createTextNode(range);
            strong.appendChild(beforeNode);//Range is not an object! Damn it!
            this.insertNodeAtSelection(getContentWindow(midas), strong, null);
        }
}

performancingMidas.hotlinkImage = function () {
	var midas = document.getElementById("performancing-message");
	
	var bfEditorTabSelected = document.getElementById("performancing-editor-tabbox").selectedIndex;
	
	if (bfEditorTabSelected == '1'){
		performancingTextEdit.hotlinkImage();
	}
	else{
		var theImageToInsert = pffEditorUI.parentWindow.performancingUI.openImageInsert();
		
		if (theImageToInsert != false){
			var img = getContentWindow(midas).document.createElement("img");
			img.setAttribute("src",theImageToInsert);
			
			if (this.prefs.getBoolPref("imageMaxWidth")) {
				img.setAttribute("style","max-width: 800px;");
			}
			
			this.insertNodeAtSelection(getContentWindow(midas), img);
			this.placeCaret(midas, img.nextSibling);
		}
	}
};

performancingMidas.uploadImage = function() {
	var midas = document.getElementById("performancing-message");
	
	var bfEditorTabSelected = document.getElementById("performancing-editor-tabbox").selectedIndex;
	
	if (bfEditorTabSelected == '1'){
		performancingTextEdit.uploadImage();
	}
	else {
		var theImageToInsert = pffEditorUI.parentWindow.performancingUI.openImageUpload();
		
		if (theImageToInsert != false){
			var img = getContentWindow(midas).document.createElement("img");
			img.setAttribute("src",theImageToInsert);
			
			if (this.prefs.getBoolPref("imageMaxWidth")) {
				img.setAttribute("style","max-width: 800px;");
			}
			
			this.insertNodeAtSelection(getContentWindow(midas), img);
			this.placeCaret(midas, img.nextSibling);
		}
	}
}

performancingMidas.insertNodeAtSelection = function(win, insertNode, type) {//type = before, after null
    // get current selection
    var sel = win.getSelection();
    //alert("sel: "+ sel + " sel.getRangeAt(0): " + sel.getRangeAt(0));

    // get the first range of the selection
    // (there's almost always only one range)
    var range = sel.getRangeAt(0);

    // deselect everything
    sel.removeAllRanges();

    // remove content of current selection from document
    //var clone = null;
    if(type == null){
        range.deleteContents();
    }

    // get location of current selection
    var container = range.startContainer;
    var pos = range.startOffset;
    if(type == "after"){
        container = range.endContainer;
        pos = range.endOffset;
    }

    // make a new range for the new selection
    range=document.createRange();

    if (container.nodeType==3 && insertNode.nodeType==3) {
        // if we insert text in a textnode, do optimized insertion
        container.insertData(pos, insertNode.nodeValue);

        // put cursor after inserted text
        range.setEnd(container, pos+insertNode.length);
        range.setStart(container, pos+insertNode.length);
    } else {
        var afterNode;
        if (container.nodeType==3) {
            // when inserting into a textnode
            // we create 2 new textnodes
            // and put the insertNode in between
            var textNode = container;
            container = textNode.parentNode;
            var text = textNode.nodeValue;

            // text before the split
            var textBefore = text.substr(0,pos);
            // text after the split
            var textAfter = text.substr(pos);

            var beforeNode = document.createTextNode(textBefore);
            var afterNode = document.createTextNode(textAfter);

            // insert the 3 new nodes before the old one
            container.insertBefore(afterNode, textNode);
            container.insertBefore(insertNode, afterNode);
            container.insertBefore(beforeNode, insertNode);

            // remove the old node
            container.removeChild(textNode);
        } else {
            // else simply insert the node
            afterNode = container.childNodes[pos];
            container.insertBefore(insertNode, afterNode);
        }
        range.setEnd(afterNode, 0);
        range.setStart(afterNode, 0);
    }

    sel.addRange(range);
}



//Places the caret inside and at the beginning of the node specified
performancingMidas.placeCaret = function(win, node) {
    var sel = getContentWindow(win).getSelection();
    var range = sel.getRangeAt(0);
    sel.removeAllRanges();
    range=document.createRange();
    range.setEnd(node, 0);
    range.setStart(node, 0);
    sel.addRange(range);
    getContentWindow(win).focus();
}

//
performancingMidas.placeCaretLite = function(win) {
    var sel = getContentWindow(win).getSelection();
    var range = sel.getRangeAt(0);
    sel.removeAllRanges();
    range=document.createRange();
    sel.addRange(range);
    getContentWindow(win).focus();
}

//For generic XHTML compliance
performancingMidas.getXHTML = function(text) {
    //Fix closing tags on single elements
	text = text.replace(/<(br|hr|img|input)((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)?(\/)?>/gi, "<$1$2 />");
	
    //Add space if it is <br style=""/> at this point
    text = text.replace(/<(br|hr|img)([^>]*)"\/>/gi, "<$1$2\" />");

    // Make sure br is closed
    text = text.replace(/<(br|hr)>/gi, "<$1 />");
	text = text.replace(/\s*<\/param>/gi, "");
	text = text.replace(/(<param[^>\/]+)\/>/gi, "$1>");
	text = text.replace(/\s*<\/embed>/gi, "");
	text = text.replace(/(<embed[^>]+>)/gi, "$1 </embed>");
	text = text.replace(/\/>\s*<\/embed>/gi, " </embed>");
	text = text.replace(/\/>\s*<\/param>/gi, " </param>");
	text = text.replace(/<\/input>/gi, "");
	
	// Add a <div class="youtube-video" wrapper to any embed or object tags
	text = text.replace(/<div[^>]+><object/gi, "<object");
	text = text.replace(/<\/object><\/div>/gi, "</object>");
	
	text = text.replace(/<object/gi, '<div class="youtube-video"><object');
	text = text.replace(/<\/object>/gi, '</object></div>');
	
	return text;
}


// Source -> Normal (note: DOM is NOT compliant at this point)
// 1) The value of the Source tab's textbox is stored in a variable and modified using RegExp's to make it DOM compliant and any other formating that should be done at this time.
// 2) The innerHTML of the Preview tab's frame is replaced with the value from the variable.
// 3) Any DOM modifications that are needed for the Normal tab are made to the Preview tab's frame.
// 4) The innerHTML of the Normal tab's editor is replaced with the innerHTML from the Preview tab's frame.
// (note: Preview handles adding the subject and just about everything else is taken from the Normal tab
performancingMidas.syncNormalTab = function(callback, args) {
    //***Begin RegExp phase***
    var text = document.getElementById("performancing-message-source").value.replace(/^\s+|\s+$/g, "");

	if (text.match(/<pre[^>]*>/i)) {
		try {
			var allMatches = text.match(/<pre[^>]*>([\s\S]+?)<\/pre>/img);//[1];
			
			for (var i = 0; i < allMatches.length; i++) {
			    var currentMatch = allMatches[i];
			    
    			var toReplace = currentMatch.match(/<pre[^>]*>([\s\S]+?)<\/pre>/im)[1];
			
    			var replaced = toReplace.replace(/</g, "&lt;");
    			replaced = replaced.replace(/>/g, "&gt;");
			
    			// $ is a special backreference char.
    			replaced = replaced.replace(/\$/g, "$$$$");
			
    			text = text.replace(toReplace, replaced);
		    }
		} catch (e) {
		}
	}

    text = text.replace(/(\r)?\n/gi, "<br/>");
    text = text.replace(/<br( \/)?>/gi, "<br/>");

    //For generic XHTML compliance whether the user wants them or not?
    text = this.getXHTML(text);

	pffEditorUI.parentWindow.gPerformancingUtil.convertTextToHTML(text, performancingMidas.finishSyncNormal, callback, args);
	return true;
}

performancingMidas.doKeyPress = function (event) {
	if (!event.ctrlKey) {
		return true;
	}
	
	switch (event.which) { 
		case 98:
			goDoCommand('cmd_bold');
		break;
		case 122:
			goDoCommand('cmd_undo');
		break;
		case 121:
			goDoCommand("cmd_redo");
		break;
		case 120:
			goDoCommand("cmd_cut");
		break;
		case 99:
			goDoCommand("cmd_copy");
		break;
		case 118:
			goDoCommand("cmd_paste");
		break;
		case 97:
			goDoCommand("cmd_selectAll");
		break;
		case 105:
			goDoCommand("cmd_italic");
		break;
		case 117:
			goDoCommand("cmd_underline");
		break;
	}
	
	return false;
};

performancingMidas.finishSyncNormal = function (text, callback, doc, args) {
	var winNormal = document.getElementById("performancing-message");
	getContentWindow(winNormal).document.body.innerHTML = text;
	
	if (callback) {
		callback(args);
	}
}

// Normal -> Source (note: DOM is compliant at this point)
// 1) The innerHTML in the Preview tab's frame is replaced with the innerHTML from the Normal tab's editor.
// 2) Any DOM modifications that are needed for the Source tab are made to the Preview tab's frame.
// 3) The innerHTML of the Preview tab's frame is then stored in a variable and further modified using RegExp's.
// 4) The value of the Source tab's textbox is then replaced with the contents of the variable.
performancingMidas.syncSourceTab = function() {
    var winNormal = document.getElementById("performancing-message");
	
    try {
        var text = getContentWindow(winNormal).document.body.innerHTML;
		
		//replace 0 or 1 newline followed by a br followed by 0 or 1 newline with a formatted br
        text = text.replace(/<br([^>]*)>[\r\f]?\n/gi, "<br$1 />");
        text = text.replace(/[\r\f]\n? ?/gi, " ");
        text = text.replace(/\n ?/gi, " ");
    
        //remove all br's at the end of the string. The editor usually adds at least one.
        text = text.replace(/<br( \/)?>$/gi, "");
    
    	if (text.match(/<pre[^>]*>/i)) {
			try {
				var toReplace = text.match(/<pre[^>]*>([\s\S]+)<\/pre>/im)[1];
				var replaced = toReplace.replace(/&lt;/g, "<");
				replaced = replaced.replace(/&gt;/g, ">");
				text = text.replace(toReplace, replaced);
			} catch (e) {
			}
		}

        //Replace any new br's entered in the message tab with newlines
        text = text.replace(/<br( \/)?>/gi,"\n");
    
        //For generic XHTML compliance whether the user wants them or not?
        text = this.getXHTML(text);
    
        document.getElementById("performancing-message-source").value = text;
    }catch(e){
	}
}

performancingMidas.stripTags = function () {
	var selectedTab = document.getElementById("performancing-editor-tabbox").selectedIndex;
	
	if (selectedTab == '1'){
		var box = document.getElementById("performancing-message-source");
		var start = box.selectionStart;
		var selection = box.value.substring(start, box.selectionEnd);
		selection = selection.replace(/<br\s*\/?>/g, "\n");
		selection = selection.replace(/<\/?p>/g, "\n");
		var strippedSelection = selection.replace(/<[^>]+>/g, " ");
		box.value = box.value.substring(0, box.selectionStart) + strippedSelection + box.value.substring(box.selectionEnd);
		box.setSelectionRange(start, strippedSelection.length + start);
	}
	else {
		var midas = document.getElementById("performancing-message");
		var oRange = getContentWindow(midas).getSelection().getRangeAt(0);
		var totalHTML = getContentWindow(midas).document.documentElement.innerHTML;
		
		var contents = oRange.extractContents();
		
		var newTotalHTML = contents.ownerDocument.documentElement.innerHTML;
		
		var start = 0;
		
		for (start = 0; start < totalHTML.length; start++) {
			if (totalHTML[start] != newTotalHTML[start]) {
				break;
			}
		}
		
		var diff = totalHTML.length - newTotalHTML.length;
		var selectedHTML = totalHTML.substring(start, start + diff);
		
		var plainText = selectedHTML.replace(/<br\s*\/?>/g, "\n").replace(/<\/?p>/g, "\n").replace(/<[^>]+>/g, "").replace(/\n/g, "<br />");
		oRange.deleteContents();
		
		var nodes = plainText.split("<br />");
		
		for (var i = nodes.length - 1; i >= 0; i--) {
			if (i != nodes.length - 1) {
				oRange.insertNode(getContentWindow(midas).document.createElement("br"));
			}
			
			var newNode = getContentWindow(midas).document.createTextNode(nodes[i]);
			oRange.insertNode(newNode);
		}
	}

	try { oRange.detach(); } catch (e) { }
}

performancingMidas.showSpecialCharToolbar = function () {
	document.getElementById("specialchar-toolbar").collapsed = !document.getElementById("specialchar-toolbar").collapsed;
}

performancingMidas.viewTab = function(tab) {
	var goingTo = tab.id;
	var tabbox = document.getElementById("performancing-editor-tabbox");
	var theTabList = ["tab-normal-edit","tab-source-edit","tab-preview-edit"];
	var comingFrom = theTabList[tabbox.selectedIndex];
	
	if (goingTo != comingFrom) {
		document.getElementById(comingFrom).setAttribute("isselected", "false");
		document.getElementById(goingTo).setAttribute("isselected", "true");

		this.prefs.setCharPref("display.state.lastviewopened", goingTo);

		switch (goingTo) {
			case "tab-normal-edit":
				if (comingFrom != 'tab-preview-edit') {
					this.syncNormalTab();
				}
				
				pffEditorUI.theSpellcheck = pffEditorUI.richSpellCheck;
				document.getElementById('firstrowtoolbar').style.visibility = '';
				tabbox.selectedIndex = 0;
				getContentWindow(document.getElementById("performancing-message")).focus();
			break;
			case "tab-source-edit":
				if (comingFrom != 'tab-preview-edit') {
					this.syncSourceTab();
				}
				
				pffEditorUI.theSpellcheck = pffEditorUI.sourceSpellCheck;
				document.getElementById('firstrowtoolbar').style.visibility = '';
				tabbox.selectedIndex = 1;
				document.getElementById("performancing-message-source").setSelectionRange(document.getElementById("performancing-message-source").textLength, document.getElementById("performancing-message-source").textLength);
				document.getElementById("performancing-message-source").focus();
			break;
			case "tab-preview-edit":
				document.getElementById('firstrowtoolbar').style.visibility = 'hidden';
				tabbox.selectedIndex = 2;
				
				if (comingFrom == 'tab-source-edit') {
					this.syncNormalTab();
				} else {
					this.syncSourceTab();
				}
				
				this.syncPreviewFromSource();
			break;
		}
	}
}

performancingMidas.syncPreviewFromSource = function() {
	var iframe = document.getElementById("performancing-preview-display");
	var text = document.getElementById("performancing-message-source").value;
	text = text.replace(/\n/g, "<br />");
	
	var dontAsk = false;
	
	try {
		var template = SCRIBEFIRE_DB.getBlogTemplate(pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.guid);
	} catch (noBlogs) {
		var template = false;
		var dontAsk = true;
	}
	
	if (!template) {
		if (dontAsk) {
			var button = 1;
			var check = { value : false };
		}
		else {
			var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
			                        .getService(Components.interfaces.nsIPromptService);
			var check = { value : true };
			var flags = 
				prompts.BUTTON_POS_0 * prompts.BUTTON_TITLE_YES
				+ prompts.BUTTON_POS_1 * prompts.BUTTON_TITLE_NO;
					
			var button = prompts.confirmEx(window,
						performancingUI.getLocaleString("livePreview"), 
						performancingUI.getLocaleString("livePreview.ask") + "\n\n" + performancingUI.getLocaleString("livePreview.warning"),
						flags, 
			            "",
						"",
						"",
						performancingUI.getLocaleString("livePreview.notAgain"), check);
		}
		
		if (button == 0) {
			pffEditorUI.parentWindow.gPerformancingUtil.setupLivePreview();
			return;
		}
		else {
			template = '<html><head><link id="performancing-preview-css" rel="stylesheet" href="chrome://scribefire/skin/blank.css" /><link rel="stylesheet" href="chrome://global/skin/global.css" /></head><body><p><b><a href="javascript:void(0);">%%SF_TITLE%%</a></b></p><p>%%SF_BODY%%</p></body></html>';
			
			if (check.value) {
				SCRIBEFIRE_DB.saveBlogTemplate(pffEditorUI.parentWindow.SCRIBEFIRE_BLOG.guid, template, false);
			}
		}
	}
	
	try {
		var head = template.match(/<head[^>]*>([\s\S]+)<\/head>/im);
		iframe.contentDocument.getElementsByTagName("head")[0].innerHTML = head[1];
	} catch (e) {
	}
	
	try {
		newTemplate = template.match(/<body[^>]*>([\s\S]+)<\/body>/im)[1];
	} catch (e) {
		newTemplate = template;
	}
	
	template = newTemplate;
	
	var bodyRE = new RegExp("%%SF_BODY%%", "g");
	var titleRE = new RegExp("%%SF_TITLE%%", "g");
	
	bodyText = template.replace(bodyRE, text).replace(titleRE, document.getElementById("performancing-editor-subject").value);
	
	iframe.contentDocument.body.innerHTML = bodyText;
}

performancingTextEdit.hotlinkImage = function () {
	var theImageToInsert = pffEditorUI.parentWindow.performancingUI.openImageInsert();
	
    if (theImageToInsert != false){
        performancingTextEdit.insertAtCursor('<img src="' + theImageToInsert + '" />');
    }
};

performancingTextEdit.uploadImage = function () {
	var theImageToInsert = pffEditorUI.parentWindow.performancingUI.openImageUpload();
	
    if (theImageToInsert != false){
        performancingTextEdit.insertAtCursor('<img src="' + theImageToInsert + '" />');
    }
};

// Used for Tag insertion in Source Editor
performancingTextEdit.insertCode = function(myCommand, codeType, mycustomstring) {
    var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
    if (!clip){
      return false;
    }
    
    
    var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
    if (!trans){
      return false;
    }
    
      trans.addDataFlavor("text/unicode");
      clip.getData(trans,clip.kGlobalClipboard);

    
    var str = null;
    var str_clipboard=new Object();
    var strLength=new Object();
    try{
      trans.getTransferData("text/unicode",str_clipboard,strLength);
  
  
      if (str_clipboard){
        str_clipboard=str_clipboard.value.QueryInterface(Components.interfaces.nsISupportsString);
      }
      if (str_clipboard){
        pastetext=str_clipboard.data.substring(0,strLength.value / 2);
      }
    }catch (e){
      //alert("No text in the clipboard, please copy something first.");
    }
    
    //var theBox = document.commandDispatcher.focusedElement;
    var theBox = document.getElementById("performancing-message-source");
    var oPosition = theBox.scrollTop;
    var oHeight = theBox.scrollHeight;
    
    
    //Get Selected text (if selected)
      var startPos = theBox.selectionStart;
      var endPos = theBox.selectionEnd;
      str = theBox.value.substring(startPos, endPos);
      //alert("Str: " +str);
 
    //if(codeType == "bbcode"){
    if( performancingMidas.prefs.getBoolPref('settings.usecss') ){
        performancingTextEdit.insertAtCursorSetup(myCommand, str_clipboard, str, theBox, mycustomstring);
    }else{
        performancingTextEdit.insertHTMLAtCursorSetup(myCommand, str_clipboard, str, theBox, mycustomstring);
    }
    
    var nHeight = theBox.scrollHeight - oHeight;
    theBox.scrollTop = oPosition + nHeight;
    
    return true;
}

performancingTextEdit.insertAtCursorSetup = function(myCommand, str_clipboard, str, theBox) {
    var bold = "<strong>";
    var boldend="<\/strong>";
    var color = "<span style=\"color: ";
    var color2 = "\">";
    var colorend = "<\/span>";
    var colorend2 = "</span>";
    var select_flag = (str != "");
    switch (myCommand){
        
      case "img":
        var theImageToInsert = pffEditorUI.parentWindow.performancingUI.openImageUpload();
		
        if(theImageToInsert != false){
            performancingTextEdit.insertAtCursor("<img src=\"" + theImageToInsert + "\"/>");
        }
        
        break;
      case "fontname":
		var fontName = document.getElementById("font-menu").selectedItem.getAttribute("value");
		document.getElementById("performancing-message-source").focus();
        
        performancingTextEdit.insertAtCursorEx("<span style=\"font-family: '"+fontName+"';\">" + str,"</span>",select_flag);
		
		break;
      case "url2":
        performancingTextEdit.insertAtCursorEx("<a href=\"\">" + str,"</a>",select_flag);
        break;
        
      case "url":
        var localeString = performancingUI.getLocaleString('midaseenterurl');
		var checkString = performancingUI.getLocaleString('openinnewwindow');
		var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                    	.getService(Components.interfaces.nsIPromptService);
		try {
			var cbUrl = pff_getClipboardContents();
			
			if (cbUrl && cbUrl.match(/^http/i)) {
				var defaultValue = cbUrl;
			}
			else {
				try {
					var defaultValue = pffEditorUI.parentWindow.content.document.location.href;
				} catch (e) {
					var defaultValue = "http://";
				}
			
				if (defaultValue.match(/^chrome/)) defaultValue = "http://";
			}
			
			if (defaultValue.match(/^chrome/)) defaultValue = "http://";
		} catch (e) {
			var defaultValue = "http://";
		}

		var input = { value: defaultValue };
		var checked = performancingMidas.prefs.getBoolPref("editor.openInNewWindow");
		var check = { value: checked };

		var okorcancel = prompts.prompt(window, localeString, localeString, input, checkString, check);
		
		if (okorcancel) {
		    performancingMidas.prefs.setBoolPref("editor.openInNewWindow", check.value);
		    
			var linkString = '<a href="' + input.value + '"';
			if (check.value) linkString += ' target="_blank"';
			linkString += '>' + str;
			
			performancingTextEdit.insertAtCursorEx(linkString, "</a>", select_flag);
		}
		
        break;
      case "bold":
        performancingTextEdit.insertAtCursorEx("<span style=\"font-weight: bold;\">" + str,"</span>",select_flag);
        break;
        
      case "italic":
        performancingTextEdit.insertAtCursorEx("<span style=\"font-style: italic;\">" + str,"</span>",select_flag);
        break;
        
      case "underline":
        performancingTextEdit.insertAtCursorEx("<span style=\"text-decoration: underline;\">" + str,"</span>",select_flag);
        break;
      
      case "strikethrough":
        performancingTextEdit.insertAtCursorEx("<span style=\"text-decoration: line-through;\">" + str,"</span>",select_flag);
        break;
        
      case "strong":
        performancingTextEdit.insertAtCursorEx("<strong>" + str,"</strong>",select_flag);
        break;
        
      case "em":
        performancingTextEdit.insertAtCursorEx("<em>" + str,"</em>",select_flag);
        break;
        
      case "blockquote":
        performancingTextEdit.insertAtCursorEx("<blockquote>" + str,"</blockquote>",select_flag);
        break;
        
      case "increasefontsize":
        performancingTextEdit.insertAtCursorEx("<big>" + str,"</big>",select_flag);
        break;
        
      case "decreasefontsize":
        performancingTextEdit.insertAtCursorEx("<small>" + str,"</small>",select_flag);
        break;
        
      case "justifyleft":
        performancingTextEdit.insertAtCursorEx("<div style=\"text-align: left;\">" + str,"</div>",select_flag);
        break;
        
      case "justifycenter":
        performancingTextEdit.insertAtCursorEx("<div style=\"text-align: center;\">" + str,"</div>",select_flag);
        break;
        
      case "justifyright":
        performancingTextEdit.insertAtCursorEx("<div style=\"text-align: right;\">" + str,"</div>",select_flag);
        break;
        
      case "justifyfull":
        performancingTextEdit.insertAtCursorEx("<div style=\"text-align: justify;\">" + str,"</div>",select_flag);
        break;
        
      case "insertorderedlist":
        var eachLineArray = str.split("\n");
        var newLineString = "";
        for(i=0; i< eachLineArray.length; i++){
          if(newLineString == ""){
            newLineString = newLineString +"<li>" + eachLineArray[i] + "</li>";
          }else{
            newLineString = newLineString +"<li>" + eachLineArray[i] + "</li>";
          }
        }
        performancingTextEdit.insertAtCursor("<ol>"	 + newLineString + "</ol>");
        break;
        
      case "insertunorderedlist":
        var eachLineArray = str.split("\n");
        var newLineString = "";
        for(i=0; i< eachLineArray.length; i++){
          if(newLineString == ""){
            newLineString = newLineString +"<li>" + eachLineArray[i] + "</li>";
          }else{
            newLineString = newLineString +"<li>" + eachLineArray[i] + "</li>";
          }
        }
        performancingTextEdit.insertAtCursor("<ul>"	 + newLineString + "</ul>");
        break;
        
      case "forecolor":
        if(gPerFormancingColorPick == false){
            gPerFormancingColorPick = true;
            var mycolor = document.getElementById("performance-color-picker").color;
            document.getElementById("performancing-message-source").focus();
            performancingTextEdit.insertAtCursorEx("<span style=\"color: " + mycolor + "\">" + str,"</span>",select_flag);
        }
        window.setTimeout(performancingTextEdit.setColorPicker, 2000);
        break;
        
      case "custom":
        var tag = prompt(performancingUI.getLocaleString("customTag"));
        if (tag) {
        	performancingTextEdit.insertAtCursorEx("<"+tag+">" + str,"</"+tag+">",select_flag);
        }
        break;
        
      default :
		performancingTextEdit.insertAtCursorEx("<" + myCommand + ">" + str, "</" + myCommand + ">", select_flag);
	break;
    }
}

performancingTextEdit.insertHTMLAtCursorSetup = function(myCommand, str_clipboard, str, theBox) {
    var bold = "<strong>";
    var boldend="<\/strong>";
    var color = "<font color=\"";
    var color2 = "\">";
    var colorend = "<\/font>";
    var colorend2 = "</span>";
    var select_flag = (str != "");
    switch (myCommand){
        
      case "img":
      /*
        var imagetag = prompt("Please enter a Image URL:", "http://");
        if (imagetag != "http://" && imagetag != null) {
            performancingTextEdit.insertAtCursor("<img src=\"" + imagetag + "\"/>");
        }
        */
        var theImageToInsert = pffEditorUI.parentWindow.performancingUI.openImageUpload();
        if(theImageToInsert != false){
            performancingTextEdit.insertAtCursor("<img src=\"" + theImageToInsert + "\"/>");
        }
        break;
        
      case "url2":
        performancingTextEdit.insertAtCursorEx("<a href=\"\">" + str,"</a>",select_flag);
        break;
      case "fontname":
		var fontName = document.getElementById("font-menu").selectedItem.getAttribute("value");
		document.getElementById("performancing-message-source").focus();
        
            performancingTextEdit.insertAtCursorEx("<font face=\""+fontName+"\">" + str,"</font>",select_flag);

		break;
      case "url":
		var localeString = performancingUI.getLocaleString('midaseenterurl');
		var checkString = performancingUI.getLocaleString('openinnewwindow');
		var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                  	.getService(Components.interfaces.nsIPromptService);

		try {
			var cbUrl = pff_getClipboardContents();

			if (cbUrl && cbUrl.match(/^http/i)) {
				var defaultValue = cbUrl;
			}
			else {
				try {
					var defaultValue = pffEditorUI.parentWindow.content.document.location.href;
				} catch (e) {
					var defaultValue = "http://";
				}

				if (defaultValue.match(/^chrome/)) defaultValue = "http://";
			}
		} catch (e) {
			var defaultValue = "http://";
		}

		var input = { value: defaultValue };
		var checked = performancingMidas.prefs.getBoolPref("editor.openInNewWindow");
		var check = { value: checked };

		var okorcancel = prompts.prompt(window, localeString, localeString, input, checkString, check);
		
		if (okorcancel) {
		    performancingMidas.prefs.setBoolPref("editor.openInNewWindow", check.value);
		    
			var linkString = '<a href="' + input.value + '"';
			if (check.value) linkString += ' target="_blank"';
			linkString += '>' + str;
			
			performancingTextEdit.insertAtCursorEx(linkString, "</a>", select_flag);
		}
        break;
        
      case "bold":
        performancingTextEdit.insertAtCursorEx("<b>" + str,"</b>",select_flag);
        break;
        
      case "italic":
        performancingTextEdit.insertAtCursorEx("<i>" + str,"</i>",select_flag);
        break;
        
      case "underline":
        performancingTextEdit.insertAtCursorEx("<u>" + str,"</u>",select_flag);
        break;
      
      case "strikethrough":
        performancingTextEdit.insertAtCursorEx("<strike>" + str,"</strike>",select_flag);
        break;
        
      case "blockquote":
        performancingTextEdit.insertAtCursorEx("<blockquote>" + str,"</blockquote>",select_flag);
        break;
        
      case "strong":
        performancingTextEdit.insertAtCursorEx("<strong>" + str,"</strong>",select_flag);
        break;
        
      case "em":
        performancingTextEdit.insertAtCursorEx("<em>" + str,"</em>",select_flag);
        break;
        
      case "increasefontsize":
        performancingTextEdit.insertAtCursorEx("<big>" + str,"</big>",select_flag);
        break;
        
      case "decreasefontsize":
        performancingTextEdit.insertAtCursorEx("<small>" + str,"</small>",select_flag);
        break;
        
      case "justifyleft":
        performancingTextEdit.insertAtCursorEx("<div align=\"left\">" + str,"</div>",select_flag);
        break;
        
      case "justifycenter"://<div align="left">
        performancingTextEdit.insertAtCursorEx("<div align=\"center\">" + str,"</div>",select_flag);
        break;
        
      case "justifyright":
        performancingTextEdit.insertAtCursorEx("<div align=\"right\">" + str,"</div>",select_flag);
        break;
        
      case "justifyfull":
        performancingTextEdit.insertAtCursorEx("<div align=\"justify\">" + str,"</div>",select_flag);
        break;
        
      case "insertorderedlist":
        var eachLineArray = str.split("\n");
        var newLineString = "";
        for(i=0; i< eachLineArray.length; i++){
          if(newLineString == ""){
            newLineString = newLineString +"<li>" + eachLineArray[i] + "</li>";
          }else{
            newLineString = newLineString +"<li>" + eachLineArray[i] + "</li>";
          }
        }
        performancingTextEdit.insertAtCursor("<ol>"	 + newLineString + "</ol>");
        break;
        
      case "insertunorderedlist":
        var eachLineArray = str.split("\n");
        var newLineString = "";
        for(i=0; i< eachLineArray.length; i++){
          if(newLineString == ""){
            newLineString = newLineString +"<li>" + eachLineArray[i] + "</li>";
          }else{
            newLineString = newLineString +"<li>" + eachLineArray[i] + "</li>";
          }
        }
        performancingTextEdit.insertAtCursor("<ul>"	 + newLineString + "</ul>");
        break;
        
      case "forecolor":
        if(gPerFormancingColorPick == false){
            gPerFormancingColorPick = true;
            var mycolor = document.getElementById("performance-color-picker").color;
            document.getElementById("performancing-message-source").focus();
            performancingTextEdit.insertAtCursorEx("<font color=\"" + mycolor + "\">" + str,"</font>",select_flag);
        }
        window.setTimeout(performancingTextEdit.setColorPicker, 2000);
        break;
        
      case "custom":
        var tag = null;

        var tag = prompt(performancingUI.getLocaleString("customTag"));

		if (tag) {
        	performancingTextEdit.insertAtCursorEx("<"+tag+">" + str,"</"+tag+">",select_flag);
		}
        break;
        
      default : 
		performancingTextEdit.insertAtCursorEx("<" + myCommand + ">" + str, "</" + myCommand + ">", select_flag);
		break;
    }
}

performancingTextEdit.setColorPicker = function() {
    gPerFormancingColorPick = false;
}

performancingTextEdit.insertAtCursor = function( aText) {
    try {
      var command = "cmd_insertText";
      var controller = document.commandDispatcher.getControllerForCommand(command);
      if (controller && controller.isCommandEnabled(command)) {
        controller = controller.QueryInterface(Components.interfaces.nsICommandController);
        var params = Components.classes["@mozilla.org/embedcomp/command-params;1"];
        params = params.createInstance(Components.interfaces.nsICommandParams);
        params.setStringValue("state_data", aText);
        controller.doCommandWithParams(command, params);
      }
    }catch (e) {
    }
}

performancingTextEdit.insertAtCursorEx = function(aText, bText, selection) {
      this.insertAtCursor(aText+bText);
      if ( !selection ) {
          this.backupCursor(bText);
      }	 
}

//Original Function by Asquella, modified by Patrick Wildenborg
performancingTextEdit.backupCursor = function(aText) {
    try {
      var command = "cmd_charPrevious";
      var controller = document.commandDispatcher.getControllerForCommand(command);
      if (controller && controller.isCommandEnabled(command)) {
        controller = controller.QueryInterface(Components.interfaces.nsICommandController);
        var params = Components.classes["@mozilla.org/embedcomp/command-params;1"];
        params = params.createInstance(Components.interfaces.nsICommandParams);
        var len = aText.length
        while( len-- > 0 ) {
            controller.doCommand(command, params);
        }
      }
    }catch (e) {
    }
}

performancingMidas.jumpBreak = function () {
	if (document.getElementById("tab-normal-edit").getAttribute("isselected") == "true") {
		var midas = document.getElementById("performancing-message");
        
		var jump = getContentWindow(midas).document.createElement("hr");
		jump.setAttribute("class", "jump");
        this.insertNodeAtSelection(getContentWindow(midas), jump, null);
	}
	else if (document.getElementById("tab-source-edit").getAttribute("isselected") == "true") {
		performancingTextEdit.insertAtCursor('<hr class="jump" />');
	}
};

performancingMidas.addTable = function () {
	var rows = prompt(performancingUI.getLocaleString("table.rows"), 2);
	var columns = prompt(performancingUI.getLocaleString("table.columns"), 2);
	
	var code = '<table border="1" style="width: '+(columns * 90)+'px; height: '+(rows * 50)+'px;"><tbody>';
	
	for (var i = 0; i < rows; i++) {
		code += "<tr>";
		
		for (var j = 0; j < columns; j++) {
			code += '<td style="width: '+Math.floor(100 / columns)+'%; height: '+Math.floor(100 / rows)+'%;"></td>';
		}
		
		code += "</tr>";
	}
	
	code += "</tbody></table>";
	
	pffEditorUI.parentWindow.performancingEditor.insertText(code);
};

performancingMidas.setFloat = function (value) {
	if (!value) value = 'none';
	
	var midas = document.getElementById("performancing-message");
    var HTMLEditor = midas.getHTMLEditor(getContentWindow(midas));
	
	var element = HTMLEditor.getSelectedElement("");
	
	if (element) {
		element.style.cssFloat = value;
		
		element.style.marginRight = '';
		element.style.marginLeft = '';
		element.style.marginTop = '10px';
		element.style.marginBottom = '10px';

		switch (value) {
			case 'left':
				element.style.marginRight = '10px';
			break;
			case 'right':
				element.style.marginLeft = '10px';
			break;
			default:
				element.style.marginTop = '';
				element.style.marginBottom = '';
			break;
		}
	}
};

function getContentWindow(frame) {
	if (frame.contentWindow.wrappedJSObject) {
		return frame.contentWindow.wrappedJSObject;
	}
	
	return frame.contentWindow;
}

function pff_getClipboardContents() {
	var clip  = Components.classes["@mozilla.org/widget/clipboard;1"].getService(Components.interfaces.nsIClipboard);
	if (!clip) return false;

	var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
	if (!trans) return false;
	trans.addDataFlavor("text/unicode");
	
	clip.getData(trans, clip.kGlobalClipboard);

	var str       = new Object();
	var strLength = new Object();

	trans.getTransferData("text/unicode", str, strLength);
	if (str) str       = str.value.QueryInterface(Components.interfaces.nsISupportsString);
	if (str) pastetext = str.data.substring(0, strLength.value / 2);
	return pastetext;
}